<!--
 * @Description: 积分维护
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 15:05:31
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="tabtop">
          <div v-for="(item, index) in contractTypelist" :key="index" @click="choose(item.id)">
            <div :class="currenindex == item.id ? 'active' : 'text'">{{ item.value }}</div>
            <div v-if="
                currenindex !== item.id &&
                currenindex !== index + 2 &&
                index !== 4
              " class="hr"></div>
          </div>
        </div>
        <el-select v-if="UserInfo.adminStatus == 1" v-model="companyId" placeholder="请选择" style="padding:10px 20px;" @change="setstationIdlist(fromDate.companyId)">
          <el-option v-for=" item in companylist" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-form v-if="currenindex<4" ref="reffromDate" class="FZYsmartIntegralSet" :inline="true" :model="formDate" label-width="160px">
          <div style="text-align: right;max-width:950px;margin:10px 0px;">
            <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUN'))!==-1" class="bottom_all" style="margin-left: 24px;" @click="save_or_updateFun()">保 存</el-button>
          </div>
          <div class="form-title">一次性奖励</div>
          <el-form-item>
            <span slot="label">新用户首次登陆</span>
            <el-input-number v-model="formDate.rule.firstLogin" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 2">
            <span slot="label">首次有效计划</span>
            <el-input-number v-model="formDate.rule.firstEffectivePlan" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <div class="form-title">功能奖励</div>
          <el-form-item>
            <span slot="label">每日登录</span>
            <el-input-number v-model="formDate.rule.loginDay" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 1">
            <span slot="label">添加机会</span>
            <el-input-number v-model="formDate.rule.addOpportunity" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 2">
            <span slot="label">用料签收</span>
            <el-input-number v-model="formDate.rule.ylSign" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 2">
            <span slot="label">计划评价</span>
            <el-input-number v-model="formDate.rule.planEvaluation" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <div class="form-title">系统奖励</div>
          <el-form-item v-if="currenindex == 1">
            <span slot="label">有效机会</span>
            <el-input-number v-model="formDate.rule.effectiveOpportunity" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 2">
            <span slot="label">下单有效计划</span>
            <el-input-number v-model="formDate.rule.orderEffectivePlan" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 3">
            <span slot="label">有效供应清单</span>
            <el-input-number v-model="formDate.rule.effectiveSuplyList" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 3">
            <span slot="label">有效运输清单</span>
            <el-input-number v-model="formDate.rule.effectiveTransportList" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 3">
            <span slot="label">有效混凝土运输</span>
            <el-input-number v-model="formDate.rule.effectiveConcreteTransport" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
          <el-form-item v-if="currenindex == 3">
            <span slot="label">有效泵送任务</span>
            <el-input-number v-model="formDate.rule.effectiveBsTask" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
            <span class="fen"> 分</span>
          </el-form-item>
        </el-form>
        <div v-if="currenindex==4" style="padding:0 20px;">
          <div v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUN'))!==-1" style="text-align: right;max-width:950px;margin:10px 0px;">
            <el-button class="bottom_all" style="margin-left: 24px;" @click="set4Fun()">保 存</el-button>
          </div>
          <div style="display: flex;max-width:950px;">
            <div class="left">
              <!-- 左侧导航 -->
              <div class="nav">
                <div style="width:100%" class="left-active">业务数据</div>
              </div>
              <!-- 数据 -->
              <div class="radio leftitem scroll" style="height:calc(100vh - 440px);">
                <el-radio-group v-model="businessId" @change="fixedTarget_listFun()">
                  <el-radio v-for="(item,index) in businessIdList" :key="index" :label="item.id">{{ item.name }}</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="center"></div>
            <!-- 检测频率设置 -->
            <div class="right">
              <div class="nav">
                <div style="width:100%" class="left-active">积分规则</div>
              </div>
              <!-- 数据 -->
              <div class="radio leftitem" style="height:calc(100vh - 440px);">
                <p v-if="businessId != 'engineerContractTotal'" class="guiZhe">
                  <span slot="label">每日开始时间：</span>
                  <el-date-picker v-model="effectiveTime" style="width:240px;" type="datetime" value-format="yyyy-MM-dd HH:mm" placeholder="请选择"></el-date-picker>
                </p>
                <template>
                  <div v-if="fList.length>0" class="FZYjiFen">
                    <div>
                      <span>小于 </span>
                      <el-input-number v-model="fList[0].maxUnit" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
                      <span>（业务单位）：</span>
                      <el-input-number v-model="fList[0].score" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
                      &nbsp;<span>分</span>
                    </div>
                    <div v-for="(item,index) in fList" :key="index">
                      <div v-if="index>0 && index<fList.length-1">
                        <span>{{fList[index-1].maxUnit}} 至 </span>
                        <el-input-number v-model="item.maxUnit" :precision="0" style="width: 80px;" :controls="false" :min="0" @change="fList[fList.length-1].minUnit = item.maxUnit"></el-input-number>
                        <span>（业务单位）：</span>
                        <el-input-number v-model="item.score" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
                        &nbsp;<span>分</span>
                        <el-link v-if="index>1" class="table_link" :underline="false" @click="dellistArr4(item.id,index)">删除区间</el-link>
                      </div>
                    </div>
                    <div class="moreScore">
                      <span>大于或等于</span>
                      <span>{{fList[fList.length-2].maxUnit}}</span>
                      <span>（业务单位）：</span>
                      <el-input-number v-model="fList[fList.length-1].score" :precision="0" style="width: 80px;" :controls="false" :min="0">
                      </el-input-number>
                      &nbsp;<span>分</span>
                    </div>
                    <p>
                      <el-link class="table_link" :underline="false" @click="addlistArr4()">添加区间</el-link>
                    </p>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
        <div v-if="currenindex==5" style="padding:0 20px;">
          <div v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUN'))!==-1" style="text-align: right;max-width:950px;margin:10px 0px;">
            <el-button class="bottom_all" style="margin-left: 24px;" @click="set5Fun()">提 交</el-button>
          </div>
          <div style="display: flex;max-width:1100px;">
            <div class="left">
              <!-- 左侧导航 -->
              <div class="nav">
                <div style="width:100%" class="left-active">自定义业务备注</div>
              </div>
              <!-- 数据 -->
              <div class="radio leftitem" style="min-height:calc(100vh - 480px);">
                <el-input v-model="form5.describeInfo" type="textarea" :rows="2" placeholder="请输入内容">
                </el-input>
              </div>
            </div>
            <div class="center" style="margin: 0 20px;width:130px;border: 1px solid #e1e5ed;border-radius: 4px;">
              <!-- 导航 -->
              <div class="nav">
                <div style="width:100%" class="left-active">设置积分</div>
              </div>
              <!-- 数据 -->
              <div class="radio leftitem " style="height:calc(100vh - 440px);">
                <el-input-number v-model="form5.integral" :precision="0" style="width: 80px;" :controls="false" :min="0"></el-input-number>
              </div>
            </div>
            <!-- 检测频率设置 -->
            <div class="right">
              <div class="nav">
                <div style="width:100%" class="left-active">积分规则</div>
              </div>
              <!-- 数据 -->
              <div class="radio leftitem" style="min-height:calc(100vh - 440px);">
                <p class="guiZhe">
                  <el-select v-model="form5.type" style="width:150px;" placeholder="请选择" @change="form5Type()">
                    <el-option label="组织" value="1"></el-option>
                    <el-option label="角色" value="2"></el-option>
                    <el-option label="人员" value="3"></el-option>
                  </el-select>
                  <el-input v-if="form5.type>1" v-model="roleSeachKey" style="width:150px;margin-left: 10px;" placeholder="请输入" prefix-icon="el-icon-search" @input="roleSeachKeyFun(roleSeachKey)">
                  </el-input>
                </p>
                <div class="FZYcsk">
                  <div>
                    <span>选择</span>
                    <div class="leftDiv scroll">
                      <el-tree ref="tree1" :data="treedata" class="tree-line" :indent="0" show-checkbox node-key="id" :props="{label:'name'}">
                      </el-tree>
                    </div>
                  </div>
                  <div>
                    <table>
                      <el-button icon="el-icon-d-arrow-right" style="width:88px;" @click="getCurrentNodeFun()"></el-button>
                    </table>
                    <table>
                      <el-button icon="el-icon-d-arrow-left" style="width:88px;" @click="delCheckboxFun()"></el-button>
                    </table>
                    <table>
                      <el-button @click="delFun()">清空已选</el-button>
                    </table>
                  </div>
                  <div>
                    <span>已选</span>
                    <div class="scroll" style="padding:10px;">
                      <el-checkbox-group v-model="checkList">
                        <el-checkbox v-for="(item, index) in checkListArr" :key="index" style="display:block;" :label="item.id">{{item.name}}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  target_list,
  save_or_update,
  fixedSave_or_update,
  fixedTarget_list,
  getList,
  grantIntegral,
  fixeddel
} from "@/api/smart/smartIntegral/smartIntegralSet.js";
import { getUserInfo } from "@/utils/auth.js";
import { getcompany } from "@/api/common.js";
import { formatTreeData } from "@/utils/utils";
import { queryPage as queryPagerole } from "@/api/basedata/role";
import {
  queryPage,
} from "@/api/basedata/organization.js";
import { queryPage as queryuserPage } from "@/api/basedata/user";
export default {
  mixins: [mixin],
  data() {
    return {
      UserInfo: '',
      companyId: '',
      companylist: [],
      /*添加表单数据*/
      contractTypelist: [
        { value: "员工积分管理", id: 1 },
        { value: "客户积分管理", id: 2 },
        { value: "供应商积分管理", id: 3 },
        { value: "固定业务配置", id: 4 },
        { value: "自定义业务配置", id: 5 },
      ],
      currenindex: 1,
      formDate: { rule: {} },
      businessIdList: [],
      businessId: '',
      fList: [],
      effectiveTime: '',
      form5: { type: '1' },
      treearr: [],//组织
      rolearr: [],//角色
      userData: [],//人员
      checkListArr: [],//已选角色
      checkList: [],//已选角色勾选
      roleSeachKey: '',//模糊搜索
    };
  },
  created() {
    this.UserInfo = getUserInfo();
    if (this.UserInfo.adminStatus == 0) {
      this.companyId = this.UserInfo.companyId
    }
    /**通过typeId为公司类型id查询所有公司 */
    getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
      this.companylist = res.data;
    });
    this.formDate.type = 1;
    this.target_listFun()
    /**获取组织 */
    const params = {
      page: 1,
      pageSize: 10000,
    };
    queryPage(params).then((res) => {
      if (res.code === 1001) {
        const { data } = res.data;
        this.treearr = formatTreeData(
          data,
          "id",
          "parentId",
          "children",
          "parent_id"
        );
        this.treedata = this.treearr
      }
    });
    let json = {
      page: 1,
      pageSize: 10000,
      roleEentrance: "entrance_manager"
    }
    queryPagerole(json).then((res) => {
      this.rolearr = res.data.data
    });
    /**获取角色 */
    /**获取人员 */
    const data = {
      page: 1,
      pageSize: 100000,
    };
    queryuserPage({
      ...data,
      userEentrance: "entrance_manager",
      enable: 1,
    }).then((res) => {
      this.userData = res.data.data
    });
  },
  methods: {
    form5Type() {
      if (this.form5.type == 1) {
        this.treedata = this.treearr
      } else if (this.form5.type == 2) {
        this.treedata = this.rolearr
      } else if (this.form5.type == 3) {
        this.treedata = this.userData
      }
    },
    set5Fun() {
      this.form5.target = this.checkListArr.map((res) => res.id)
      this.form5.target = this.form5.target.join(',')
      console.log(JSON.parse(JSON.stringify(this.form5)))
      grantIntegral(this.form5).then((res) => {
        if (res.code == 1001) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
        }
      })
    },
    delFun() {
      this.$refs.tree1.setCheckedKeys([]);
      this.checkListArr = []
    },
    delCheckboxFun() {
      for (let i = 0; i < this.checkListArr.length; i++) {
        if (this.checkList.indexOf(this.checkListArr[i].id) != -1) {
          this.checkListArr.splice(i, 1)
          i = i - 1
        }
      }
      this.checkList = []
      this.$refs.tree1.setCheckedNodes(this.checkListArr);
    },
    getCurrentNodeFun() {
      let data = this.$refs.tree1.getCheckedNodes(true)
      this.checkListArr = [...this.checkListArr, ...data]
      let obj = {};
      this.checkListArr = this.checkListArr.reduce((cur, next) => {
        obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
        return cur;
      }, []) //设置cur默认类型为数组，并且初始值为空的数组
    },
    /**保存积分规则查询 */
    set4Fun() {
      if (this.businessId != 'engineerContractTotal' && this.effectiveTime == '') {
        this.$message({
          message: '请选择每日开始时间',
          type: 'warning'
        });
      } else {
        this.fList.forEach((e) => {
          e.effectiveTime = this.effectiveTime
        })
        fixedSave_or_update({ fList: this.fList }).then((res) => {
          if (res.code == 1001) {
            this.$message({
              message: '保存成功',
              type: 'success'
            });
          }
        })
      }
    },
    /**选择业务数据后积分规则查询 */
    fixedTarget_listFun() {
      fixedTarget_list({ businessId: this.businessId, companyId: this.companyId }).then((res) => {
        if (res.data.length == 0) {
          this.fList = [
            { minUnit: 0, maxUnit: 1, businessId: this.businessId, score: 0, companyId: this.companyId },
            { minUnit: 1, maxUnit: 2, businessId: this.businessId, score: 0, companyId: this.companyId },
            { minUnit: 2, maxUnit: 99999, businessId: this.businessId, score: 0, companyId: this.companyId },
          ]
          console.log(this.fList);
        } else {
          this.fList = res.data
        }
      })
    },
    dellistArr4(id, k) {
      if (id) {
        fixeddel({ id: id }).then((res) => {
          if (res.code == 1001) {
            this.fixedTarget_listFun()
          }
        })
      } else {
        this.fList.splice(k, 1)
      }
    },
    addlistArr4() {
      let a = this.fList[this.fList.length - 2].maxUnit
      let json = { minUnit: a, maxUnit: a + 1, businessId: this.businessId, score: 0, companyId: this.companyId }
      this.fList[this.fList.length - 1].minUnit = a + 1
      this.fList.splice(this.fList.length - 1, 0, json)
    },
    choose(num) {
      this.currenindex = num;
      this.$data.formDate = this.$options.data().formDate
      this.formDate.type = this.currenindex
      this.formDate.mold = 1
      if (num < 4) {
        this.target_listFun();
      } else if (num == 4) {
        /** 业务数据列表 */
        getList({ ID: '' }).then((res) => {
          this.businessIdList = res.data.data
          this.businessId = this.businessIdList[0].id
          this.fixedTarget_listFun()
        })
      } else if (num == 5) {
        console.log(1);
      }
    },
    /** 获取积分设置(员工、客户、供应商) */
    target_listFun() {
      console.log(this.formDate.type);
      target_list({ type: this.formDate.type, companyId: this.companyId }).then((res) => {
        if (res.data == null) {
          this.formDate.mold = 1
        } else {
          this.formDate = { ... this.formDate, ...res.data }
          this.formDate.mold = 2
          /**字符串转数组转再转{}对象 */
          let arr = JSON.parse(this.formDate.rule)
          this.formDate.rule = {}
          arr.forEach((e) => {
            for (let k in e) {
              this.formDate.rule[k] = e[k];
            }
          })
        }
      })
    },
    /** 新增或修改积分规则配置(员工、客户、供应商) */
    save_or_updateFun() {
      this.formDate.companyId = this.companyId
      let arr = []
      /**{}对象转数组转再字符串 */
      console.log(this.formDate.rule);
      for (let k in this.formDate.rule) {
        arr.push({ [k]: this.formDate.rule[k] == undefined ? 0 : this.formDate.rule[k] })
      }
      this.formDate.rule = JSON.stringify(arr)
      console.log(JSON.parse(JSON.stringify(this.formDate.rule)))
      save_or_update(this.formDate).then((res) => {
        if (res.code == 1001) {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          this.target_listFun()
        }
      })
    },
    roleSeachKeyFun(name) {
      if (this.form5.type == 2) {
        if (name) {
          this.treedata = this.rolearr.filter((res) => res.name.includes(name))
          this.$forceUpdate()
        } else {
          this.treedata = this.rolearr
          this.$forceUpdate()
        }
      } else if (this.form5.type == 3) {
        if (name) {
          this.treedata = this.userData.filter((res) => res.name.includes(name))
          this.$forceUpdate()
        } else {
          this.treedata = this.userData
          this.$forceUpdate()
        }
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.dialog-title {
  font-size: 16px;
  font-weight: bold;
  padding-right: 40px;
}
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
.tabtop {
  width: 950px;
}
.form-title {
  font-size: 18px;
  margin: 10px 0;
}
.FZYsmartIntegralSet {
  padding: 0 20px;
  max-width: 1300px;
  .el-form-item {
    width: 300px;
    .fen {
      color: #606266;
    }
  }
}
.nav {
  padding: 0 20px;
  height: 56px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  background: #e1e5ed;
  color: #000000;
  > div {
    font-size: 12px;
    font-weight: bold;
    height: 48px;
    //width: 50%;
    @include discen;
  }

  .left-active {
    color: $bg_color;
    border-radius: 8px 8px 0px 0px;
  }
}
.center {
  width: 24px;
  height: 100%;
}
.left {
  border: 1px solid rgba(225, 229, 237, 1);
  flex: 2;
  border-radius: 4px;
}
.right {
  overflow: hidden;
  flex: 5;
  border: 1px solid rgba(225, 229, 237, 1);
  border-radius: 4px;
}
.radio {
  overflow: auto;
  padding: 20px;
  .radio-bg {
    height: 28px;
  }
  .el-radio {
    padding: 5px;
  }
}
.radio::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}
.radio::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
.radio::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}
.radio::-webkit-scrollbar-thumb:hover {
  background: $bg_color;
}
.radio::-webkit-scrollbar-corner {
  background: $bg_color;
}
.guiZhe {
  width: 365px;
  margin: auto;
  padding-bottom: 20px;
}
.FZYjiFen {
  width: 450px;
  margin: auto;
  padding-left: 20px;
  > div {
    padding-bottom: 10px;
    span {
      display: inline-block;
    }
    span:nth-of-type(1) {
      min-width: 70px;
      text-align: center;
    }
  }
  .moreScore {
    > span:nth-of-type(1) {
      min-width: 100px;
    }
    > span:nth-of-type(2) {
      min-width: 50px;
      text-align: center;
    }
    > span:nth-of-type(3) {
      min-width: 98px;
    }
  }
  > p {
    width: 310px;
    text-align: center;
  }
}
.FZYjiFen2 {
  width: 180px;
  margin: auto;
  > div {
    padding-bottom: 10px;
  }
}
.FZYcsk {
  display: flex;
  > div {
    flex: 1;
    > div {
      height: calc(100vh - 555px);
      border: 1px solid #dcdfe6;
      overflow: auto;
    }
  }
  > div:nth-of-type(2) {
    width: 150px;
    padding-top: 40px;
    > table {
      width: 100%;
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style>
